package com.huifaapp.mall.api;



import com.blankj.utilcode.util.NetworkUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.bean.BaseBeans;
import com.huifaapp.mall.bean.UploadImagBean;
import com.huifaapp.mall.uitils.BitmapUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiManager {


//    public static final String BASE_NIUPAI_URL = "http://www.jhjvip.cn:8080/mall/mobile/";
//    public static final String BASE_HTML_URL= "http://www.jhjvip.cn/huifaShop/html/";
//    public static final String BASE_IMAGE_URL = APP.isDebug?"http://192.168.199.107:8080/mall/mobile/"
//            :"http://www.jhjvip.cn:8080/mall/mobile/";


//    public static final String BASE_NIUPAI_URL ="http://develop.jhjvip.cn:8080/mall/mobile/";
//    public static final String BASE_HTML_URL= "http://develop.jhjvip.cn:8080/huifaShop/html/";

    public static final String BASE_NIUPAI_URL ="http://develop.jhjvip.cn:8080/mall/mobile/";
    public static final String BASE_HTML_URL= "http://develop.jhjvip.cn:8080/huifaShop/html/";

//
//    public static final String BASE_NIUPAI_URL="http://47.92.134.181:8080/mall/mobile/";
//    public static final String BASE_HTML_URL="http://47.92.134.181:8080/huifashop/html/";

//    public static final String BASE_NIUPAI_URL ="http://192.168.1.105:8080/mall/mobile/";
//    public static final String BASE_HTML_URL= "http://192.168.1.105/huifaShop/html/";
//    public static final String BASE_IMAGE_URL = APP.isDebug?"http://192.168.1.102:8080/mall/mobile/"
//    :"http://www.jhjvip.cn:8080/mall/mobile/";
//    public static  String WELCOME_IMAGE="http://www.jhjvip.cn:8080/mall/mobile/welcome/url";
    public static String PAY_WEIXIN=BASE_NIUPAI_URL+"weixin/pay";
    private volatile static Retrofit retrofitInstance = null;
    private static ApiService apiService = null;
    private static ApiManager mApiManager = null;

    /**
     * 物流
     */
    public static String WU_LIU="http://down.huifakeji.com/dist/index.html#/logistics";
    /**
     * 欢迎页
     */
    public static String WELCOME_IMAGE=BASE_NIUPAI_URL+"indexpage/index";
    /**
     * 版本升级
     */
    public static String PROJECT_VERSION=BASE_NIUPAI_URL+"project/version";
    /**
     * 获取验证码
     */
    public static String LOGIN_CODE=BASE_NIUPAI_URL+"login/code";
    /**
     * 注册
     */
    public static String LOGIN_REG=BASE_NIUPAI_URL+"login/reg";
    /**
     *登录
     */
    public static String LOGIN_IN=BASE_NIUPAI_URL+"login/in";
    /**
     * 重置密码
     */
    public static String USERS_CHGPWD=BASE_NIUPAI_URL+"users/chgpwd";
    /**
     *首页轮播
     */
    public static String INDEX_BANNERS=BASE_NIUPAI_URL+"index/banners";
    /**
     *模块
     */
    public static String INDEX_MODELS=BASE_NIUPAI_URL+"index/models";
    /**
     * 广告图一
     */
    public static String INDEX_ADVERTONE=BASE_NIUPAI_URL+"index/advertOnes";
    /**
     * 首页淘二手信息
     */
    public static String INDEX_SECHAND=BASE_NIUPAI_URL+"index/secHand";
    /**
     * 首页发现好货
     */
    public static String INDEX_FINDGOOD=BASE_NIUPAI_URL+"index/findgood";
    /**
     * 广告位二
     */
    public static String INDEX_ADVERTTWO=BASE_NIUPAI_URL+"index/advertTwo";
    /**
     * 排行榜信息
     */
    public static String INDEX_RANKING=BASE_NIUPAI_URL+"index/ranking";
    /**
     * 热门活动
     */
    public static String INDEX_HOTING=BASE_NIUPAI_URL+"index/hoting";
    /**
     * 惠生钱
     */
    public static String INDEX_CREMONEY=BASE_NIUPAI_URL+"index/creMoney";
    /**
     * 到帐消息推送
     */
    public static String INDEX_CLINTMSG=BASE_NIUPAI_URL+"index/clintMsg";
    /**
     * 生钱广告位
     */
    public static String INDEX_ADVERTTHREE=BASE_NIUPAI_URL+"index/advertThree";

    /**
     * 整点特卖广告位
     */
    public static String ZT_SPECIAL_ADVERT=BASE_NIUPAI_URL+"special/advertlist";
    /**
     * 整点特卖时间点
     */
    public static String ZT_SPECIAL_GETSPECIALTIME=BASE_NIUPAI_URL+"special/getspecialtime";
    /**
     * 整点特卖产品
     */
    public static String ZT_SPECIAL_SPECIALLIST=BASE_NIUPAI_URL+"special/speciallist";

    /**
     *支付详情页获取用户默认地址
     */
    public static String USERSPAY_GETADDRBYUSERID=BASE_NIUPAI_URL+"userspay/getAddrByUserId";
    /**
     * 详情进入的支付详情页
     */
    public static String USERSPAY_PAYDETAIL=BASE_NIUPAI_URL+"userspay/paydetail";
    /**
     * 京东二合一链接
     */
    public static String JD_SYNCJDSPREADURL=BASE_NIUPAI_URL+"jd/syncJdSpreadUrl";
    /**
     * 购物车
     */
    public static String USERS_MYSHOPPINGCART=BASE_NIUPAI_URL+"users/myshoppingcart";
    /**
     *购物车数量增减接口
     */
    public static String ADJUSTSHOPPINGCARTCOUNT=BASE_NIUPAI_URL+"users/adjustshoppingcartCount";
    /**
     *购物车到支付详情页接口
     */
    public static String USERSPAY_SHOPPINGCARTPAY=BASE_NIUPAI_URL+"userspay/shoppingcartpay";
    /**
     * 商品详情页数量变化计算实付金额接口
     */
    public static String USERSPAY_GETACTUALPAYBYCOUNT=BASE_NIUPAI_URL+"userspay/getActualPayByCount";
    /**
     *微信支付
     */
    public static String WXPAY_PAY=BASE_NIUPAI_URL+"wxpay/pay";


    /**
     * JD分享
     */
    public static final String JD_PRESHARE=BASE_NIUPAI_URL+"share/single";

    /**
     *友惠分享
     */
    public static final String PRODUCT_PRESEND=BASE_NIUPAI_URL+"share/single";

    /**
     * 购物车删除
     */
    public static final String DELSHOPPINGCART=BASE_NIUPAI_URL+"users/delshoppingcart";

    /**
     * 购物车收藏
     */
    public static final String USERS_ADDCOLLECT=BASE_NIUPAI_URL+"users/addcollect";
    /**
     *支付订单实付款
     */
    public static final String OEDERS_CALACTUALMONEY=BASE_NIUPAI_URL+"orders/calActualMoney";
    /**
     * 支付余额
     */
    public static final String USERS_BALANCE=BASE_NIUPAI_URL+"users/balance";

    /**
     * 是否展示惠生钱模块
     */
    public static final String INDEX_ISSHOWCREMONEY=BASE_NIUPAI_URL+"index/isShowCreMoney";
    /**
     *邀请vip
     */
    public static final String USER_INVITE_VIP=BASE_NIUPAI_URL+"users/invite/vip";
    /**
     * vip列表
     */
    public static final String USERS_INVITE_LISTVIP=BASE_NIUPAI_URL+"/users/invite/listVip";
    /**
     *商品库存
     */
    public static final String GOODS_SKU_COUNT=BASE_NIUPAI_URL+"goods/sku/count";
    /**
     * 每日必推轮播图
     */
    public static final String EVERYDAY_BANNER=BASE_NIUPAI_URL+"everyday/banner";
    /**
     *爆款分享和一键分享
     */
    public static final String EVERYDAY_LIST=BASE_NIUPAI_URL+"everyday/list";
    /**
     * 爆款分享详情
     */
    public static final String EVERYDAY_HOTDETAIL=BASE_NIUPAI_URL+"everyday/hotDetail";
    /**
     * 今日精选
     */
    public static final String EVERYDAY_JINXUAN=BASE_NIUPAI_URL+"everyday/jinxuan";
    /**
     * 分享App
     */
    public static final String PROJECT_SHAREAPP=BASE_NIUPAI_URL+"project/shareApp";
    /**
     * 进入我要开店
     */
    public static final String USERS_OPENSTO=BASE_NIUPAI_URL+"users/openstore/isOpen";
    /**
     *申请开店
     */
    public static final String USERS_OPENSTORE_RUZHU=BASE_NIUPAI_URL+"users/openstore/ruzhu";
    /**
     *获得开店的轮播图与方案
     */
    public static final String  USERS_OPENSTORE_INDEX=BASE_NIUPAI_URL+"users/openstore/index";
    /**
     *活动模块详情
     */
    public static final String  MARKET_ACTIVITYDETAIL=BASE_NIUPAI_URL+"market/activityDetail";
    /**
     * 轮播图详情
     */
    public static final String MARKET_BANNERDETAIL=BASE_NIUPAI_URL+"market/bannerDetail";
    /**
     *商品广告位详情
     */
    public static final String MARKET_ADVERTDETAIL=BASE_NIUPAI_URL+"market/advertDetail";
    /**
     *领取优惠券
     */
    public static final String COUPON_RECEIVE=BASE_NIUPAI_URL+"coupon/receive";
    /**
     * 系统优惠券列表
     */
    public static final String COUPON_SYS_LIST=BASE_NIUPAI_URL+"coupon/sys/list";
    /**
     * 店铺分享
     */
    public static final String SHARE_STORE=BASE_NIUPAI_URL+"share/store";
    /**
     *绑定微信
     */
    public static final String USERS_BINDWX=BASE_NIUPAI_URL+"users/bindwx";
    /**
     *
     */
    public static final String PROJECT_WELCOM=BASE_NIUPAI_URL+"project/welcome";

    /**
     * 客服
     */
    public static final String KEFU="http://chat56.live800.com/live800/chatClient/chatbox.jsp?companyID=944015&configID=155782&jid=9694995927";
    /*

            年利率详情
     */
    public  static  final  String DETAIL = BASE_NIUPAI_URL+"user/living/yearRate/detail";
    /*
            生钱总数
     */
    public  static  final  String LiMonLiLOG = BASE_NIUPAI_URL+"user/living/livingMoney/log";
    /*
        花钱记录
     */
    public  static  final  String ConsumeLOG = BASE_NIUPAI_URL+"user/living/consume/log";
    /*
            晒年利率

     */
    public  static  final  String  YearRate = BASE_NIUPAI_URL+"user/living/share/myYearRate";
    /*
            会生钱首页
     */
    public  static  final  String Index = BASE_NIUPAI_URL+"user/living/index";
        /*
                分享友惠家
         */
        public static  final  String INvite = BASE_NIUPAI_URL+"user/living/share/invite/index";
        /*
                获取邀请好友的连接

         */
        public  static  final  String Share = BASE_NIUPAI_URL+"user/living/share/invite";
        /*
                f分享海报
         */
        public static  final  String shreHB =  BASE_NIUPAI_URL+"user/living//HB/index";
        /*
                有趣链接主页
         */
        public  static  final  String Interest = BASE_NIUPAI_URL+"user/living/interest/index";
        /*
                有趣链接
         */
        public  static  final  String SHAREyouqu = BASE_NIUPAI_URL+"user/living/share/interest";
        /*
              助理列表
         */
        public  static  final  String  HELPLIST= BASE_NIUPAI_URL+"/user/living/help/list";
        /*
                申请银行卡提现
         */
        public  static  final  String BankAppley = BASE_NIUPAI_URL+"/withDrawals/wx/apply";
        /*
                手续费
         */
        public  static  final  String FEE = BASE_NIUPAI_URL+"withDrawals/wx/fee";
        /*
                查询余额
         */
        public  static  final   String balance =BASE_NIUPAI_URL+"users/balance";
        /*
        bank列表
         */
        public  static  final  String BankLIst=BASE_NIUPAI_URL+"withDrawals/bank/list";





    /**
     * 获取Retrofit实例
     *
     * @return Retrofit
     */
    public static ApiService getMYApiService() {
        if (null == retrofitInstance) {
            synchronized (Retrofit.class) {
                if (null == retrofitInstance) { // 双重检验锁,仅第一次调用时实例化

                    retrofitInstance = new Retrofit.Builder()
                            // baseUrl总是以/结束，@URL不要以/开头
                            .baseUrl(BASE_NIUPAI_URL)
                            // 使用OkHttp Client
                            .client(buildOKHttpClient())
                            // 集成RxJava处理
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            // 集成Gson转换器
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    if (apiService == null) {
                        apiService = retrofitInstance.create(ApiService.class);
                    }
                }
            }
        }

        return apiService;
    }


    
    private ApiManager(){}
    public static ApiManager getInstance() {
        if ((mApiManager==null)) { // 双重检验锁,仅第一次调用时实例化
       
        synchronized (ApiManager.class) {
            if (mApiManager == null) {
                mApiManager = new ApiManager();
                retrofitInstance = new Retrofit.Builder()
                        // baseUrl总是以/结束，@URL不要以/开头
                        .baseUrl(BASE_NIUPAI_URL)
                        // 使用OkHttp Client
                        .client(buildOKHttpClient())
                        // 集成RxJava处理
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        // 集成Gson转换器
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
        }
        }
        return mApiManager;
    }
    /**
     * 构建OkHttpClient
     *
     * @return OkHttpClient
     */
    private static OkHttpClient buildOKHttpClient() {
        // 添加日志拦截器，非debug模式不打印任何日志
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//        loggingInterceptor.setLevel(AppUtil.isDev() ? HttpLoggingInterceptor.Level.HEADERS : HttpLoggingInterceptor.Level.NONE) ;

        return new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)                       // 添加日志拦截器
                //.addInterceptor(buildTokenInterceptor())                // 添加token拦截器
                .addNetworkInterceptor(buildCacheInterceptor())           // 添加网络缓存拦截器
                .cache(getCache())                                        // 设置缓存文件
                .retryOnConnectionFailure(true)                           // 自动重连
                .connectTimeout(15, TimeUnit.SECONDS)                     // 15秒连接超时
                .readTimeout(20, TimeUnit.SECONDS)                        // 20秒读取超时
                .writeTimeout(20, TimeUnit.SECONDS)                       // 20秒写入超时
                .build();
    }

    /**
     * 获取缓存对象
     *
     * @return Cache
     */
    private static Cache getCache() {
        // 获取缓存目标,SD卡
//        File cacheFile = new File(AppUtil.getContext().getCacheDir(), ResourceUtil.getString(R.string.app_name_en));
        File cacheFile = new File(APP.getInstance().getCacheDir(), "cache");
        // 创建缓存对象,最大缓存50m
        return new Cache(cacheFile, 1024 * 1024 * 20);
    }

    /**
     * 构建缓存拦截器
     *
     * @return Interceptor
     */
    private static Interceptor buildCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                // 无网络连接时请求从缓存中读取
                if (!NetworkUtils.isConnected()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }

                // 响应内容处理
                // 在线时缓存5分钟
                // 离线时缓存4周
                Response response = chain.proceed(request);
                if (NetworkUtils.isConnected()) {
                    int maxAge = 300;
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                            .build();
                } else {
                    // 无网络时，设置超时为4周
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
    }

    /**
     * 构建GSON转换器
     *
     * @return GsonConverterFactory
     */
    private static GsonConverterFactory buildGsonConverterFactory() {


        GsonBuilder builder = new GsonBuilder();
        builder.setLenient();

        // 注册类型转换适配器
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                return null == json ? null : new Date(json.getAsLong());
            }
        });

        Gson gson = builder.create();
        return GsonConverterFactory.create(gson);
    }
    /**
     * 设置头
     */
//    private static Interceptor addHeaderInterceptor() {
//        Interceptor headerInterceptor = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request originalRequest = chain.request();
//                Request.Builder requestBuilder = originalRequest.newBuilder()
//                        // Provide your custom header here
//                        .header("token", (String) SpUtils.get("token", ""))
//                        .method(originalRequest.method(), originalRequest.body());
//                Request request = requestBuilder.build();
//                return chain.proceed(request);
//            }
//        };
//        return headerInterceptor;
//    }
//    public class HeaderInterceptor implements Interceptor {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request originalRequest = chain.request();
////            ArrayMap<String, String> headers = BaseApp.getAppContext().getRequestHeader();
//            //如果公共请求头不为空,则构建新的请求
//            if (headers != null) {
//                Request.Builder requestBuilder = originalRequest.newBuilder();
//
//                for (String key : headers.keySet()) {
//                    requestBuilder.addHeader(key, headers.get(key));
//                }
//                requestBuilder.method(originalRequest.method(), originalRequest.body());
//                return chain.proceed(requestBuilder.build());
//            }
//            return chain.proceed(originalRequest);
//        }
//    }

    /**
     * 处理数据.把BaseBean<T>转换成<T>  并指定指定线程
     *
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<BaseBeans<T>, T> handlResult() {
        return new ObservableTransformer<BaseBeans<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseBeans<T>> upstream) {
                return upstream.flatMap(new Function<BaseBeans<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(BaseBeans<T> tBaseBean) throws Exception {
                        return createResobj(tBaseBean);
                    }
                }).subscribeOn(io.reactivex.schedulers.Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    /**
     * 根据code码 判断是否成功获取数据
     *
     * @param resobj
     * @param <T>
     * @return 成功返回数据 ,不成功返回自定义异常
     */
    private static <T> Observable<T> createResobj(final BaseBeans<T> resobj) {

        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> e) throws Exception {
                if (null == resobj) {
                    e.onError(new ApiException("", "数据为空!"));
                } else {
                    if (resobj.getCode().equals("10000")) { //成功返回 数据
                        e.onNext(resobj.getData());
                    } else {   //失败返回 错误码和info
                        e.onError(new ApiException(resobj.getCode(), resobj.getMsg()));
                    }
                }


            }
        });
    }

    public <T> T createApi(Class<T> clazz) {
        return retrofitInstance.create(clazz);
    }
    /**
     * 获取接口
     * @return
     */
    public  ApiService  getApiServer(){

        return retrofitInstance.create(ApiService.class);

    }
    /**
     * 上传图片方法
     *
     * @param filePath
     * @return
     */
    public Observable<UploadImagBean> uploadImage(String filePath) {
        File file = BitmapUtils.getimage(filePath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return getApiServer().upLoad("http://file.jhjvip.cn:8888/image-server/uploadImage",requestFile);
    }

    public Observable<UploadImagBean> uploadImage2(String filePath) {
        File file = BitmapUtils.getimage(filePath);
//        File file = new File(filePath);
//        File file = new File(filePath);//filePath 图片地址
        String token = "ASDDSKKK19990SDDDSS";//用户token
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型
//                .addFormDataPart(ParamKey.TOKEN, token);//ParamKey.TOKEN 自定义参数key常量类，即参数名
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file", file.getName(), imageBody);//imgfile 后台接收图片流的参数名

        List<MultipartBody.Part> parts = builder.build().parts();

        return getApiServer().uploadMemberIcon("http://file.jhjvip.cn:8888/image-server/uploadImage",parts);
    }


}